package com.xingongchang.baolebei.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

import com.external.androidquery.callback.AjaxStatus;
import com.external.maxwin.view.XListView;
import com.insthub.BeeFramework.fragment.BaseFragment;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;
import com.xingongchang.baolebei.BaolebeiApp;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.activity.SendTopicActivity;
import com.xingongchang.baolebei.activity.SigninActivity;
import com.xingongchang.baolebei.activity.TopicDetailActivity;
import com.xingongchang.baolebei.adapter.MorePopWindow;
import com.xingongchang.baolebei.adapter.TopicAdapter;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.protocol.AD;
import com.xingongchang.baolebei.protocol.PAGINATED;
import com.xingongchang.baolebei.protocol.SESSION;

public class ForumFragment extends BaseFragment implements OnClickListener,
  BusinessResponse, XListView.IXListViewListener {

	private View view;
	private UserInfoModel mUserInfoModel;
	private XListView xlistView;
	private boolean isSetAdapter = true;
	private ImageView more_menu, send_topic;
	private TopicAdapter mTopicAdapter;
	private ViewPager viewPager;
	private List<ImageView> imageViews; // 滑动的图片集合
	private int currentItem = 0; // 当前图片的索引号
	private ScheduledExecutorService scheduledExecutorService;
	private ImageLoader imageLoader;
	private View headerView;
	private SharedPreferences shared;
	private SharedPreferences.Editor editor;
	private String uid;
    private  FrameLayout frameLayout;
//    private ImageView more_tips;
    MorePopWindow morePopWindow;
    int case_id;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		imageLoader = ImageLoader.getInstance();
//		case_id=getIntent().getIntExtra("topicid", 0);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.forum, null);
//		more_tips=(ImageView) view.findViewById(R.id.more_tips);
		imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity())); 
		shared = getActivity().getSharedPreferences("userInfo", 0);
		editor = shared.edit();
		editor.putInt("ab",case_id).commit();
		headerView = LayoutInflater.from(getActivity()).inflate(
				R.layout.forum_header_view, null);
		viewPager = (ViewPager) headerView.findViewById(R.id.viewpager);
		xlistView = (XListView) view.findViewById(R.id.topic_list);
		frameLayout=(FrameLayout) view.findViewById(R.id.frameent01);
		xlistView.setPullLoadEnable(true);
		xlistView.setRefreshTime();
		xlistView.setEmptyView(frameLayout);
		xlistView.addHeaderView(headerView);
		xlistView.setXListViewListener(this, 1);
		xlistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				int topicId = mUserInfoModel.topicList.get(position - 2).topicid;
				// }
				Intent intent = new Intent(getActivity(),
						TopicDetailActivity.class);
				intent.putExtra("topicid", topicId);
				startActivity(intent);

			}
		});
		
        //东西
		more_menu = (ImageView) view.findViewById(R.id.more_menu);
		send_topic = (ImageView) view.findViewById(R.id.send_topic);
		more_menu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				morePopWindow = new MorePopWindow(getActivity(),mUserInfoModel.Usign);
				morePopWindow.showPopupWindow(more_menu);
			}
		});
		send_topic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				uid = shared.getString("uid", "");
				if (uid.equals("")) {
					Intent intent = new Intent(getActivity(),
							SigninActivity.class);
					startActivity(intent);
					getActivity().overridePendingTransition(
							R.anim.push_buttom_in, R.anim.push_buttom_out);
				} else {
					Intent intent = new Intent(getActivity(),
							SendTopicActivity.class);
					startActivity(intent);
				}
			}
		});

		imageViews = new ArrayList<ImageView>();
		if (null == mUserInfoModel) {
			mUserInfoModel = new UserInfoModel(getActivity());
//			mUserInfoModel.getTopic();
			mUserInfoModel.getAd();
			SESSION session=SESSION.getInstance();
			mUserInfoModel.getTopicUserInfo(session.uid);
			mUserInfoModel.getLetter();
		}
		mUserInfoModel.addResponseListener(this);

		return view;
	}

	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};

	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {

		if (url.endsWith(ProtocolConst.TOPIC)) {
			xlistView.stopRefresh();
			xlistView.stopLoadMore();
			xlistView.setRefreshTime();

			setContent();
			PAGINATED paginated = PAGINATED.fromJson(jo
					.optJSONObject("paginated"));
			if (0 == paginated.more) {
				xlistView.setPullLoadEnable(false);
			} else {
				xlistView.setPullLoadEnable(true);
			}
		} else if (url.endsWith(ProtocolConst.AD)) {

			if (mUserInfoModel.adList.size() > 0
					&& mUserInfoModel.adList != null) {
				headerView.setVisibility(View.VISIBLE);
				LayoutParams params = viewPager.getLayoutParams();
				params.width = getDisplayMetricsWidth();
				params.height = (int) (params.width * 1.0 / 32 * 13);
				viewPager.setLayoutParams(params);
				imageViews.clear();
				// 初始化图片资源
				for (int i = 0; i < mUserInfoModel.adList.size(); i++) {
					ImageView imageView = new ImageView(getActivity());
					AD ad = mUserInfoModel.adList.get(i);
					imageLoader.displayImage(ad.imgUrl, imageView,
							BaolebeiApp.options);
					imageView.setScaleType(ScaleType.CENTER_CROP);
					imageViews.add(imageView);
					imageView.setTag(ad.topicid);
					imageView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							int topicId = (Integer) v.getTag();
							Intent intent = new Intent(getActivity(),
									TopicDetailActivity.class);
							intent.putExtra("topicid", topicId);
							startActivity(intent);
						}
					});
				}
				viewPager.setAdapter(new MyAdapter());
				viewPager.setOnPageChangeListener(new MyPageChangeListener());
				scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
				// 每5秒钟切换一次图片显示
				scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 5,
						TimeUnit.SECONDS);
			} else {
				headerView.setVisibility(View.GONE);
			}

		}
		//判断是否有私信未读
//		if(url.endsWith(ProtocolConst.USER_STATUS_LETTER)){
//			if(mUserInfoModel.Usign==1){
//				more_tips.setVisibility(View.VISIBLE);
//			}else{
//				more_tips.setVisibility(View.GONE);
//			}
//		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onResume() {

		super.onResume();
		uid = shared.getString("uid", "");
		if (!uid.equals("")) {
			SESSION session=SESSION.getInstance();
			mUserInfoModel.getTopicUserInfo(session.uid);
//			mUserInfoModel.getTopic();
			mUserInfoModel.getAd();
			mUserInfoModel.getLetter();
		}
		MobclickAgent.onPageStart("Profile");
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onRefresh(int id) {
		// TODO Auto-generated method stub
		isSetAdapter = true;
//		mUserInfoModel.getTopic();
		mUserInfoModel.getAd();
		mUserInfoModel.getLetter();
	}

	@Override
	public void onLoadMore(int id) {
		// TODO Auto-generated method stub
		isSetAdapter = false;
//		mUserInfoModel.getTopicMore(case_id);
	}

	public void setContent() {

		if (mTopicAdapter == null) {

			if (mUserInfoModel.topicList.size() != 0) {
				mTopicAdapter = new TopicAdapter(getActivity(),
						mUserInfoModel.topicList);
				xlistView.setAdapter(mTopicAdapter);
			}

		} else {

			if (isSetAdapter == true) {
				xlistView.setAdapter(mTopicAdapter);
			} else {
				mTopicAdapter.list = mUserInfoModel.topicList;
				mTopicAdapter.notifyDataSetChanged();
			}
		}

	}

	@Override
	public void onStart() {
		
		super.onStart();
	}

//	@Override
//	public void onStop() {
//		// 当Activity不可见的时候停止切换
//		scheduledExecutorService.shutdown();
//		super.onStop();
//	}

	/**
	 * 执行切换任务
	 * 
	 * @author luohao
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (viewPager) {
				currentItem = (currentItem + 1) % imageViews.size();
				handler.obtainMessage().sendToTarget();
			}
		}

	}

	private class MyPageChangeListener implements OnPageChangeListener {

		public void onPageSelected(int position) {
			currentItem = position;
		}

		public void onPageScrollStateChanged(int arg0) {
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
	}

	/**
	 * 顶部帖子图片广告
	 * 
	 * @author luohao
	 */
	private class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return imageViews.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(imageViews.get(arg1));
			return imageViews.get(arg1);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

		@Override
		public void finishUpdate(View arg0) {
		}
	}

	// 获取屏幕宽度
	public int getDisplayMetricsWidth() {
		int i = getActivity().getWindowManager().getDefaultDisplay().getWidth();
		int j = getActivity().getWindowManager().getDefaultDisplay()
				.getHeight();
		return Math.min(i, j);
	}

}
